/**
 iTextUploader
 (C) 2008 MyselftDev (myselftdev@gmail.com)
 
 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; version 2
 of the License.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

/* Revision: $Id: AppController.m 120 2009-04-27 20:11:16Z myselftdev $ */

#import "AppController.h"

BOOL checkLock()
{
	NSString *read = [NSString stringWithContentsOfFile:[@LOCK_FILE stringByExpandingTildeInPath] encoding:NSASCIIStringEncoding error:nil];
	
	if(read == nil)
	{
		return NO;
	}
	else
	{
		NSInteger val = [read integerValue];
		if(val < 1)
		{
			return NO;
		}
		else
		{
			return (kill(val, 0)) ? NO : YES;
		}
	}
	
	return NO;
}

@implementation AppController

- (id)init
{
	if(self = [super init])
	{
		data = [ [PreferencesData alloc] init];
		import = [ [ITUImport alloc] init];
	}
	return self;
}

- (id)dealloc
{
	[data release];
	[import release];
	
	[super dealloc];
}

- (void)startRequestAutomatic:(BOOL)automatic
{
	if(automatic)
	{
		NSUInteger interval = [[data getData:@"AutomaticUploadInterval"] unsignedIntValue];
		NSUInteger counter = [[data getData:@"Counter"] unsignedIntValue];
		counter++;
		if( (counter % interval) != 0)
		{
			[data setValue:[NSNumber numberWithUnsignedInt:counter] forData:@"Counter"];
			NSLog(@"Not executing this time. Counter is %u, Interval is %u", counter, interval);
			return;
		}
		else
		{
			NSLog(@"Executing this time.");
			[data setValue:[NSNumber numberWithUnsignedInt:0] forData:@"Counter"];
		}
	}
	
	// When the application is called directly from the command line, we should ignore automatic upload settings
	if(automatic && ![[data getData:@"AutomaticUpload"] boolValue])
	{
		NSLog(@"Automatic upload disabled");
		return;
	}
	
	NSURL *theURL = [NSURL URLWithString:@BASEURL];
	NSString *hostName = [theURL host];
	if(!hostName)
		return;
	
	[[Reachability sharedReachability] setHostName:hostName];
	NetworkStatus status = [[Reachability sharedReachability] remoteHostStatus];
	
	if(status == NotReachable)
	{
		NSLog(@"Host unreachable");
		return;
	}
	
	// See above :)
	if(automatic && ![[data getData:@"AutomaticUploadNetwork"] boolValue] && status != ReachableViaWiFiNetwork)
	{
		NSLog(@"Automatic upload over carrier data network disabled");
		return;
	}
	
	NSLog(@"Starting request from AppController");
	
	import.delegate = self;
	import.username = [data getData:@"username"];
	import.password = [data getData:@"password"];
	import.lastId = [[data getData:@"lastid"] unsignedIntValue];
	
	//[NSThread detachNewThreadSelector:@selector(startRequest) toTarget:import withObject:nil];
	[import startRequest];
}

- (void)setStatus:(NSNumber*)status
{
        NSLog(@"Set status: %d", [status intValue]);
                
        switch ([status intValue]) {
                case kImportComplete:
                		NSLog(@"Completed. Message: %@", import.returnData);
                		
                		NSUInteger currentTimestamp = (NSUInteger) [ [NSDate date] timeIntervalSince1970];
						[data setValue:[NSNumber numberWithUnsignedInteger:currentTimestamp] forData:@"lastupload"];
						if(import.lastId > 0)
						{
							NSLog(@"Updated lastid - old: %u, new: %u", [[data getData:@"lastid"] unsignedIntValue], import.lastId);
							[data setValue:[NSNumber numberWithUnsignedInt:import.lastId] forData:@"lastid"];
						}
                        break;
                
                case kImportError:
                        NSLog(@"Error. Message: %@", import.returnData);
                        break;
                
                case kImportStatusMessagesNoNewElements:
                        NSLog(@"There aren't new elements to be imported");
                        break;
                        
                case kImportStatusStarting:
                        NSLog(@"Starting");
                        break;
                
                case kImportStatusLoadingAddressBook:
                        NSLog(@"Loading Address Book...");
                        break;
                
                case kImportStatusReceivedAddressBook:
                        NSLog(@"Parsing Address Book...");
                        break;
                
                case kImportStatusPreparingData:
                        NSLog(@"Preparing Data...");
                        break;
                        
                case kImportStatusUploading:
                        NSLog(@"Uploading...");
                        break;
                        
                default:
                        NSLog(@"Working...");
                        break;
        }
}

@end